<?php


namespace App\Http\Controllers\H5;

use App\Common\Constant;
use App\Common\JwtAuth;
use App\Common\ResponseCode;
use App\Common\Tools;
use App\Http\Controllers\BaseController;
use App\Http\Middleware\CustomerAuth;
use App\Models\Customer\Customer;
use App\Params\H5\GetSmsCodeParams;
use App\Params\H5\LoginParams;
use App\Repository\CustomerRepository;
use App\Services\Auth\AuthService;
use App\Services\Customer\CustomerService;
use App\Traits\SmsTrait;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

/**
 * 权限相关控制器
 *
 * @package App\Http\Controllers\H5
 */
class AuthController extends BaseController
{
    use SmsTrait;

    public function __construct()
    {
        $this->middleware(CustomerAuth::class, [
            'except' => ['register', 'login', 'getSmsCode']
        ]);
    }

    /**
     * 获取手机验证码
     *
     * @return
     * @throws \Exception
     */
    public function getSmsCode()
    {
        $param = GetSmsCodeParams::create();
        if(!in_array($param->getScene(), Constant::SMS_SCENE_LIST)) {
            return $this->fail(ResponseCode::PARAM_ILLEGAL);
        }
        // 判断手机号是否存在
        if($param->getCustomerId()) {
            $customer = CustomerRepository::getInstance()->getByPhone($param->getMobile());
            if($param->getScene() == Constant::SMS_SCENE_REGISTER) {
                if(!is_null($customer)) {
                    return $this->fail(ResponseCode::CUSTOMER_PHONE_REGISTERED);
                }
            } else if($param->getScene() == Constant::SMS_SCENE_LOGIN) {
                if(is_null($customer)) {
                    return $this->fail(ResponseCode::PHONE_NOT_FOUND);
                }
            }
        }

        $code = $this->createSmsCode($param->getScene(), $param->getMobile());
        // 发送短信验证码 暂时还没有弄到免费的短信服务
        // todo

        return $this->success(['code' => $code]);
    }

    /**
     * H5端用户注册
     *
     * @param Request $request
     * @return
     * @throws
     */
    public function register(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $phone = $request->input('phone');
        $code = $request->input('code');

        // 判断参数
        if(empty($username) || empty($password) || empty($phone) || empty($code)) {
            return $this->fail(ResponseCode::PARAM_ILLEGAL);
        }

        // 判断用户名是否存在
        $customer = CustomerService::getInstance()->getByUsername($username);
        if(!is_null($customer)) {
            return $this->fail(ResponseCode::CUSTOMER_USERNAME_REGISTERED);
        }
        // 判断手机号合法
        $validator = Validator::make(['mobile' => $phone], ['mobile' => ['regex:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/']]);
        if($validator->fails()) {
            return $this->fail(ResponseCode::PHONE_FORMAT_ILLEGAL);
        }
        // 判断手机号是否存在
        $customer = CustomerRepository::getInstance()->getByPhone($phone);
        if(!is_null($customer)) {
            return $this->fail(ResponseCode::PHONE_CODE_ERROR);
        }
        // 校验用户注册的验证码
        AuthService::getInstance()->checkCaptcha(Constant::SMS_SCENE_REGISTER, $phone, $code);

        // 写入用户表
        $customer = new Customer();
        $customer->username = $username;
        $customer->secret = Tools::getUniqid();
        $customer->password = Hash::make($password . $customer->secret);
        $customer->mobile = $phone;
        $customer->customer_bn = $username;
        $customer->nickname = $username;
        $customer->head_portrait = 'https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/newmusic/img/default_b91837ae.png';
        $customer->realname = $username;
        $customer->last_login_at = Carbon::now()->toDateTimeString();
        $customer->save();
        return $this->success([
            'token' => '',
            'customer_info' => [
                'username' => $username,
                'head_portrait' => $customer->head_portrait
            ]
        ]);
    }

    /**
     * 会员登录（获取token）
     *
     * @throws
     * @return
     */
    public function login()
    {
        $param = LoginParams::create();

        // 验证码登录
        if($param->getLoginType() == Constant::LOGIN_WAY_VCODE) {
            // 校验验证码
            $checkSmsCode = $this->verifySmsCode(Constant::SMS_SCENE_LOGIN, $param->getMobile(), $param->getSmsCode());
            if(!$checkSmsCode) {
                return $this->fail(ResponseCode::PHONE_CODE_ERROR);
            }
        }

        // 获取客户
        $customer = CustomerService::getInstance()->getByMobile($param->getMobile());
        // 如果客户不存在则自动注册
        if(is_null($customer)) {
            $customer = CustomerService::getInstance()->autoRegister($param->getMobile());
        }

        // 生成 token
        $token = JwtAuth::getInstance()->setType(Constant::JWT_TYPE_CUSTOMER)->setUserName($customer->nickname)->setUserId($customer->customer_id)->encode()->getToken();
        // 更新登录信息
        CustomerService::getInstance()->updateLoginInfo($customer->customer_id);
        return $this->success(
            [
                'token' => $token,
                'customer_id' => $customer->customer_id,
                'customer_bn' => $customer->customer_bn,
                'nickname' => $customer->nickname
            ]);
    }
}
